package cn.bailin233.gateway.config;

import cn.bailin233.gateway.filter.ServiceGatewayFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;


@Configuration
public class GatewayConfig {
    @Autowired
    ServiceGatewayFilter serviceGatewayFilter;

    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        RouteLocatorBuilder.Builder routes = builder.routes();
        routes
                .route("system-service",
                        r -> r.path("/system/**")
                                .filters(f -> f.stripPrefix(1))   //添加过滤器去掉前缀
                                .uri("lb://system-service"))   //lb: 使用nacos中是本地负载均衡策略
                .route("user-service",
                        r -> r.path("/user/**")
                                .filters(f -> f.stripPrefix(1)
                                        .filters(serviceGatewayFilter))//添加access-token过滤器
                                .uri("lb://user-service"));
        return routes.build();
    }

    // 网关解决跨域问题 CORS（全称Cross-Origin Resource Sharing，跨站资源共享），是用于限制资源访问的一种方式，不被除允许外的站点访问
    @Bean
    public CorsWebFilter corsFilter() {
        System.out.println("添加跨域头");
        final CorsConfiguration config = new CorsConfiguration();
        // 允许所有的请求来源
        config.addAllowedOrigin("http://localhost:8080");
        config.addAllowedOrigin("http://localhost:8081");
        // 允许所有请求头
        config.addAllowedHeader("*");
        // 允许所有请求方法，例如get，post等
        config.addAllowedMethod("*");
        //允许携带cookie
        config.setAllowCredentials(true);
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        //对所有经过网关的请求都生效
        source.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(source);
    }
}
